﻿@model Orchard.MediaLibrary.ViewModels.ImportMediaViewModel

@using Orchard.MediaLibrary.WebSearch
@using Orchard.MediaLibrary.WebSearch.Providers
@using System.Linq

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    @{
        Script.Require("jQuery").AtFoot();
        Script.Require("Knockout").AtFoot();

        Style.Include("orchard-mediaproviders-admin.css");
        Style.Include("orchard-websearch-admin.css");
        Style.Require("FontAwesome");

        var webSearchProviders = WorkContext.Resolve<IEnumerable<IWebSearchProvider>>();

        var hasValidProvider = webSearchProviders.Any();
        var hasValidApiKey = webSearchProviders.Any(provider => provider.IsValid());
        var apiNames = webSearchProviders.Select(provider => provider.Name);
    }

    @Display.Metas()
    @Display.HeadScripts()
    @Display.HeadLinks()
    @Display.StyleSheetLinks()
</head>
<body>
    <div id="websearch-main">
        @if (!hasValidProvider)
        {
            <div id="message-api">
                @T("You need to enable a Web Search provider feature like \"Media Library Web Search - Bing\".")
            </div>
            return;
        }
        @if (!hasValidApiKey)
        {
            <div id="message-api">
                @T("You need to define an API Key in the Media settings before being able to use this feature.")
            </div>
            return;
        }
        <form data-bind="submit: doSearch">
            <div class="query-container">
                <div id="query" class="media-websearch-input-field">
                    <input type="text" autofocus placeholder="@T("Search")" />
                </div>

                <div id="icon" class="media-websearch-search-icon">
                    <button type="submit" class="fa fa-search"></button>
                </div>

                <div id="media-websearch-api-selector-container" class="media-websearch-api-selector-container">
                    <select id="media-websearch-api-selector" name="ApiNames" class="media-websearch-api-selector">
                        @foreach (var provider in webSearchProviders)
                        {
                            <option value="@provider.Name" @(provider.IsValid() ? "" : "disabled")>@provider.Name</option>
                        }
                    </select>
                </div>
            </div>
        </form>

        <ul id="websearch-results" data-bind="foreach: results">
            <li data-bind="style: { backgroundImage: 'url(' + data.ThumbnailUrl + ')' }, css:  { 'has-focus': hasFocus(), 'selected': selected() }">
                <div class="overlay">
                    <p class="filename" data-bind="text: getFilename()"></p>
                    <p class="dimensions" data-bind="text: data.Width + ' x ' +  data.Height + ' - ' + kilobytes() + ' KB'"></p>
                </div>
            </li>
        </ul>

    </div>

    <div id="websearch-properties">
        <article data-bind="with: focus">
            <h1>@T("PROPERTIES")</h1>
            <div class="thumbnail" data-bind="style: { backgroundImage: 'url(' + data.ThumbnailUrl + ')' }"></div>
            <div class="dimensions"><em>@T("Dimensions:")</em> <span data-bind="text: data.Width + ' x ' +  data.Height"></span></div>
            <div class="filename"><em>@T("Filename:")</em> <span data-bind="text: getFilename()"></span></div>
            <div class="filesize"><em>@T("Size:")</em> <span data-bind="text: kilobytes() + ' KB'"></span></div>
            <div class="actions">
                <a class="source button" data-bind="attr: {href: data.PageUrl}" target="_blank">@T("Page")</a>
                <a class="media button" data-bind="attr: {href: data.ImageUrl}" target="_blank">@T("Open")</a>
            </div>
        </article>

        <div id="websearch-properties-selection" data-bind="visible: selection().length">
            <h1>@T("SELECTION")</h1>
            <button id="button-import"> @if (Model.Replace == null) { <text>@T("Import")</text> } else { <text>@T("Replace")</text> } </button>
            <ul data-bind="foreach: selection">
                <li>
                    <div class="selection" data-bind="click: $parent.focus, style: { backgroundImage: 'url(' + data.ThumbnailUrl + ')' }">
                        <div class="selection-overlay">
                            <div class="selection-progress" data-bind="css: status(), attr: { 'title': tooltip() == '' ? null : tooltip() }"></div>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </div>

    @using (Script.Foot())
    {
        <script type="text/javascript">
        //<![CDATA[
        $(function () {
            function SearchResult(data) {
                var self = this;

                // values
                self.data = data;
                self.hasFocus = ko.observable();
                self.selected = ko.observable();
                self.status = ko.observable('');
                self.tooltip = ko.observable('');

                // operations
                self.setData = function (value) {
                    self.data = value;
                };

                self.getFilename = function () {
                    var value = self.data.ImageUrl;
                    return value.substr(value.lastIndexOf("/") + 1);
                };

                self.kilobytes = function () {
                    return Math.round(data.Size/1024);
                };
            }

            function WebSearchViewModel() {
                var self = this;

                // values
                self.selection = ko.observableArray([]);
                self.focus = ko.observable();
                self.results = ko.observableArray();

                self.doSearch = function () {
                    var query = $(".media-websearch-input-field > input").val();

                    var selectedApi = $("#media-websearch-api-selector-container > #media-websearch-api-selector").val();

                    var url = "@Url.HttpRouteUrl("", new { Area = "Orchard.MediaLibrary.WebSearch", Controller = "WebSearchApi" })";

                    $.ajax({
                        type: "GET",
                        url: url,
                        data: {
                            query: query,
                            providerType: selectedApi
                        },
                    }).done(function (msg) {
                        var results = msg;
                        self.clearSelection();
                        self.results([]);
                        for (var i = 0; i < results.length; i++) {
                            self.results.push(new SearchResult(results[i]));
                        }
                    });
                };

                self.clearSelection = function () {
                    // unselect previous elements
                    self.selection().forEach(function (item) {
                        item.selected(false);
                    });

                    self.selection([]);
                };

                self.focus.subscribe(function (oldValue) {
                    if (oldValue) {
                        oldValue.hasFocus(false);
                    }
                }, this, "beforeChange");

                self.focus.subscribe(function (newValue) {
                    if (newValue) {
                        newValue.hasFocus(true);
                    }
                });

                self.toggleSelect = function (searchResult) {
                    var index = $.inArray(searchResult, self.selection());
                    if (index == -1) {
                        self.selection.push(searchResult);
                        searchResult.selected(true);
                    } else {
                        self.selection.remove(searchResult);
                        searchResult.selected(false);
                    }

                    self.focus(searchResult);
                };

                self.select = function (searchResult) {
                    var index = $.inArray(searchResult, self.selection());
                    if (index == -1) {
                        self.clearSelection();
                        self.selection([searchResult]);
                        searchResult.selected(true);
                    }

                    self.focus(searchResult);
                };
            };

            var viewModel = new WebSearchViewModel();
            ko.applyBindings(viewModel);

            $("#websearch-results").on("click", "li", function (e) {
                var searchResult = ko.dataFor(this);
                @if(Model.Replace == null) {
                    <text>
                    if (e.ctrlKey) {
                        viewModel.toggleSelect(searchResult);
                    } else {
                        viewModel.select(searchResult);
                    }
                    </text>
                } else {
                    <text>
                    viewModel.select(searchResult);
                    </text>
                }
            }).on("contextmenu", "li", function (e) {
                var searchResult = ko.dataFor(this);
                viewModel.toggleSelect(searchResult);
                return false;
            });

            $("#button-import").on("click", function (e) {
                viewModel.selection().forEach(function (item) {
                    var url = item.data.ImageUrl;
                    item.status("uploading");
                    item.tooltip("");
                    @if (Model.Replace == null) {
                        <text>
                        $.post('@Url.Action("Import")', {
                            folderPath: '@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.FolderPath))',
                            type: '@HttpUtility.JavaScriptStringEncode(Model.Type)',
                            url: url,
                            __RequestVerificationToken: '@Html.AntiForgeryTokenValueOrchard()'
                        })
                        </text>
                    } else {
                        <text>
                        $.post('@Url.Action("Replace")', {
                            replaceId: '@HttpUtility.JavaScriptStringEncode(Model.Replace.Id.ToString())',
                            type: '@HttpUtility.JavaScriptStringEncode(Model.Type)',
                            url: url,
                            __RequestVerificationToken: '@Html.AntiForgeryTokenValueOrchard()'
                        })
                        </text>
                    }
                   .done(function (data) {
                       if (data.error) {
                           item.status("failure");
                           item.tooltip(data.error);
                       } else {
                           item.status("success");
                           item.tooltip("Media imported successfully.");
                           @if(Model.Replace != null) {
                               <text>
                               window.parent.$("a.button.close")[0].click();
                               </text>
                           }
                       }
                   })
                   .fail(function (jqXhr, data) {
                       console.log("failed: " + JSON.stringify(textStatus));
                       item.status("failure");
                   })
                   .always(function () {
                   });
                });
            });
        })
        //]]>
        </script>
    }

    @Display.FootScripts()
</body>
</html>